package com.bcsq.todolistdemo.util;


import android.graphics.Bitmap;
import android.util.Log;
import android.widget.Toast;

import com.bcsq.todolistdemo.progress.ProgressListener;
import com.bcsq.todolistdemo.progress.ProgressRequestBody;

import org.json.JSONObject;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 图片上传
 * 视频上传
 */
public class HttpUtil {
    private static OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000, TimeUnit.MILLISECONDS)
            .readTimeout(10000,TimeUnit.MILLISECONDS)
            .writeTimeout(10000, TimeUnit.MILLISECONDS).build();
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");

    private static String tag = "HttpUtils";
    private static String httpUrl = "http://39.104.85.239:8080/minio/uploadFile";


    /**
     * 视频上传
     * @param url           上传路径
     * @param listener      进度条监听器
     * @param callback      上传后数据回调
     * @param files         上传文件
     */
    public static void postFile(String url, final ProgressListener listener, okhttp3.Callback callback, File...files){

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        Log.i("chen","files[0].getName()=="+files[0].getName());
        //第一个参数要与Servlet中的一致
        builder.addFormDataPart("fileObject",files[0].getName(),
                RequestBody.create(MediaType.parse("application/octet-stream"),files[0]));

        MultipartBody multipartBody = builder.build();

        Request request  = new Request.Builder().url(url).post(new ProgressRequestBody(multipartBody,listener)).build();
        okHttpClient.newCall(request).enqueue(callback);
    }


    /**
     * 上传图片
     * @param data              图片信息
     * @param screenWidth       压缩图片最小宽度
     * @param screenHeight      压缩图片最小高度
     * @param imgPath           图片路径
     */
    public static void post(byte [] data, int screenWidth, int screenHeight, String imgPath){
        try{
//            URL url = new URL(httpUrl);
//            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//
//            conn.setRequestMethod("POST");
//            conn.setRequestProperty("Connection", "keep-alive");
//            conn.setRequestProperty("Accept", "*/*");
//            conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + tag);
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            OutputStream out = conn.getOutputStream();
//            out.write(("--" + tag + "\r\n").getBytes());
//            String fileName = "IMG_" + new SimpleDateFormat("yyyy-MM-dd_HHmmSS").format(new Date()) + ".jpg";
//            out.write(("Content-Disposition: form-data; name=\"fileObject\"; filename=\"" + fileName + "\"\r\n").getBytes());
//            out.write(("Content-Type:image/jpeg\r\n\r\n").getBytes());

            Bitmap bitmap = BitmapUtils.createBitmap(data, 90, screenWidth, screenHeight);
            post(httpUrl, bitmap);
//            bitmap = BitmapUtils.calculateInSampleSize(bitmap, screenWidth, screenHeight);
//            data = BitmapUtils.getBitmapData(bitmap);
//            out.write(data);
//            out.write(data);
//            out.write(("\r\n\r\n--" + tag + "--\r\n").getBytes());
//            out.flush();
//            out.close();
//
//            int responseCode = conn.getResponseCode();
//            if (responseCode == HttpURLConnection.HTTP_OK){
//                responseCallBack(conn.getInputStream());
//            }else {
//                Toast.makeText(null, "上传图片失败，错误码：" + responseCode, Toast.LENGTH_SHORT).show();
//            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static void post(String httpUrl, Bitmap bitmap){
        byte [] data ;
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + tag);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStream out = conn.getOutputStream();
            out.write(("--" + tag + "\r\n").getBytes());
            String fileName = "IMG_" + new SimpleDateFormat("yyyy-MM-dd_HHmmSS").format(new Date()) + ".jpg";
            out.write(("Content-Disposition: form-data; name=\"fileObject\"; filename=\"" + fileName + "\"\r\n").getBytes());
            out.write(("Content-Type:image/jpeg\r\n\r\n").getBytes());

//            Bitmap bitmap = BitmapUtils.getBitmap(imgPath);

//            bitmap = BitmapUtils.calculateInSampleSize(bitmap, screenWidth, screenHeight);
            data = BitmapUtils.getBitmapData(bitmap);
            out.write(data);
            out.write(data);
            out.write(("\r\n\r\n--" + tag + "--\r\n").getBytes());
            out.flush();
            out.close();

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK){
                responseCallBack(conn.getInputStream());
            }else {
                Toast.makeText(null, "上传图片失败，错误码：" + responseCode, Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){

        }

    }

    /**
     * 上传图片后的返回结果
     * @param inputStream
     */
    public static void responseCallBack(InputStream inputStream){
        String formatData = null;
        try {
            //接收上传图片后的服务器返回数据
            int len = -1;
            byte [] resultData = new byte[1024];

            while ((len = inputStream.read(resultData)) != -1){
                formatData = new String(resultData, 0 , len);
            }
            Log.i("chen", formatData);
            JSONObject jsonObject = new JSONObject(formatData);
            String imageUrl =  (String) jsonObject.get("imageUrl");
            Log.i("imageUrl" ,imageUrl);
            inputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
